export default class SocketService {

    static instance = null
    // socketService对象
    ws = null
    // 连接状态
    connected = false
    // 发送重试次数
    sendRetryCount = 0
    // 连接重试次数
    connectRetryCount = 0
    // 储存回调函数
    callBackMapping = {}


    static get Instance() {
        if (!this.instance) {
            this.instance = new SocketService()
        }
        return this.instance
    }

    connect() {
        if (!window.WebSocket) {
            return console.log('浏览器不支持websocket')
        }
        this.ws = new WebSocket('ws://localhost:9998')

        this.ws.onopen = () => {
            console.log('服务端连接成功......')
            this.connected = true
            this.connectRetryCount = 0
        }
        // 两种情况
        // 当连接服务器失败
        // 连接成功后, 服务器关闭了
        this.ws.onclose = () => {
            console.log('服务端连接失败......')
            this.connected = false
            this.connectRetryCount++
            setTimeout(() => this.connect(), 500 * this.connectRetryCount)
        }

        this.ws.onmessage = (msg) => {
            let recvData = JSON.parse(msg.data)
            let socketType = recvData.socketType
            
            // 判断回调函数是否存在
            if (this.callBackMapping[socketType]) {
                let action = recvData.action
                if (action === 'getData') {
                    let realData = JSON.parse(recvData.data)
                    this.callBackMapping[socketType].call(this, realData)
                } else if (action === 'fullScreen') {
                    // 同步切换全屏
                    this.callBackMapping[socketType].call(this, recvData)
                } else if (action === 'themeChange') {
                    // 同步切换皮肤
                    this.callBackMapping[socketType].call(this, recvData)
                }
            }
        }

    }


    // 回调函数的注册
    registerCallBack(socketType, callBack) {
        this.callBackMapping[socketType] = callBack
    }

    // 取消某一个回调函数
    unRegisterCallBack(socketType) {
        this.callBackMapping[socketType] = null
    }

    // 发送数据
    send(data) {
        if (this.connected) {
            this.sendRetryCount = 0
            this.ws.send(JSON.stringify(data))
        } else {
            // 重试次数越多,等待时间越长
            this.sendRetryCount++
            setTimeout(() => this.send(data), 500 * this.sendRetryCount)
        }
    }

}